package org.example.emp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.emp.dto.DepartmentDto;
import org.example.emp.mapper.DepartmentMapper;
import org.example.emp.mapper.EmployeeMapper;
import org.example.emp.pojo.Department;
import org.example.emp.pojo.Employee;
import org.example.emp.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *DepartmentServiceImpl继承ServiceImpl, DepartmentServiceImpl实现DepartmentService接口
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper , Department> implements DepartmentService {

    /**
     * 对象组合
     */
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 对象组合
     */
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 根据id查询部门信息及其下所有员工的信息
     * @param id
     * @return
     */
    @Override
    public DepartmentDto getDepartmentAndEmployeeById(int id) {
        DepartmentDto departmentDto = departmentMapper.getDepartmentAndEmployeeById(id);
        return departmentDto;
    }

    /**
     * 根据部门id删除部门，以及将删除部门的员工状态改为禁用，等待再次分配
     * @param id
     * @return
     */
    @Transactional
    @Override
    public boolean deletedDepartmentAndEmployeeById(int id) {
        //1.查询出该部门下有哪些员工信息
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("department_id", id);
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper);
        //2.改变该部门下所有员工的状态值(Employee -> status = 0)
        for (Employee employee : employeeList) {
            employee.setStatus(0);
            employeeMapper.updateById(employee);
        }
        //3.删除部门信息(Department)
        int temp = departmentMapper.deleteById(id);
        if (temp == 0){
            return false;
        }
        return true;
    }

    /**
     * 修改部门信息
     * @param department
     * @return
     */
    @Override
    public boolean updateDepartment(Department department) {
        int temp = departmentMapper.updateDepartmentById(department);
        if(temp != 0){
            return true;
        }
        return false;
    }
}
